# 对pymysql进行二次封装
import pymysql
from lib.config import config
from lib.logger import Logger

class MySQLClient(object):
    logger = Logger()
    def __init__(self, host=None, port=None, user=None, password=None, db=None):
        # 如果实例化时传入参数，则以传入参数为准，若不传，则读取配置文件传参
        self.dbInfo = {
            "host":host if host else config['database']['ip'],
            "port":port if port else int(config['database']['port']),
            "user":user if user else config['database']['user'],
            "password":password if password else config['database']['password'],
            "db":db if db else config['database']['db'],
            "cursorclass": pymysql.cursors.Cursor
        }



    def select(self, sql):
        """
        执行查询操作
        :param sql: 查询的sql语句
        :return: 查询结果集的数量
        """
        with pymysql.connect(**self.dbInfo) as connection:
            with connection.cursor() as cursor:
                self.logger.debug(sql)
                return cursor.execute(sql)

    def execute(self, sqlList):
        """
        执行查询操作
        :param sql: 查询的sql语句
        :return: 查询结果集的数量
        """
        with pymysql.connect(**self.dbInfo) as connection:
            with connection.cursor() as cursor:
                try:
                    for sql in sqlList:
                        self.logger.debug(sql)
                        cursor.execute(sql)

                except Exception as e:
                    connection.rollback()
                else:
                    connection.commit()